package com.sky.controller.common;

import com.sky.annotation.AutoFill;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

//通用
@RestController
@RequestMapping("/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil ;
    /**
     * 上传图片
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> uploadImage( MultipartFile file) throws IOException {
        log.info("文件上传");
        try {
            String originFilename = file.getOriginalFilename();
            // 截取扩展名
            String suffix = originFilename.substring(originFilename.lastIndexOf("."));
            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString() + suffix;
            String url = aliOssUtil.upload(file.getBytes(), newFilename);
            return Result.success(url);
        } catch(Exception e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败");
        }
    }
}
